package view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;

import model.dao.ResourceDAO;
import model.entity.ResourceEntity;

import org.springframework.beans.factory.annotation.Autowired;

import utils.Constants;

public class BusquedaTab extends JPanel implements ActionListener, MouseListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JTextField txtNombre;
	private JTextField txtPrefix;
	private JTextField txtSecuencial;

	private FwkButton btnFind;
	private FwkMenuItem btnInfo;
	private FwkMenuItem btnModify;
	private FwkMenuItem btnDelete;
	private FwkMenuItem btnNew;

	private FwkButton toolInfo;
	private FwkButton toolModify;
	private FwkButton toolDelete;
	private FwkButton toolNew;
	private FwkButton toolNewSearch;

	private JPopupMenu popupMenu;
	private SortedTable<ResourceEntity> results;
	private ResultadosResourcesModel resultsModel;
	
	@Autowired
	private ResourceDAO resource;

	public BusquedaTab() {
		initComponents();
		this.setLayout(new BorderLayout());
		JToolBar bar = createToolBar();
		bar.setFloatable(false);
		this.add(bar, BorderLayout.NORTH);
		JPanel form = createForm();
		this.add(form, BorderLayout.CENTER);
		JPanel results = createResultPanel();
		this.add(results, BorderLayout.SOUTH);
		createRightClickMenu();
		addListeners();
	}

	private void showPopup(MouseEvent e) {
		if (e.isPopupTrigger()) {
			Point p = e.getPoint();
			int rowNumber = results.rowAtPoint(p);
			ListSelectionModel model = results.getSelectionModel();
			model.setSelectionInterval(rowNumber, rowNumber);
			popupMenu.show(e.getComponent(), e.getX(), e.getY());
		}
	}

	private void addListeners() {
		btnInfo.addActionListener(this);
		btnModify.addActionListener(this);
		btnDelete.addActionListener(this);
		btnNew.addActionListener(this);

		btnFind.addActionListener(this);
		results.addMouseListener(this);
		toolInfo.addActionListener(this);
		toolModify.addActionListener(this);
		toolDelete.addActionListener(this);
		toolNew.addActionListener(this);
		toolNewSearch.addActionListener(this);

	}

	private JToolBar createToolBar() {
		JToolBar bar = new JToolBar(JToolBar.HORIZONTAL);
		bar.add(toolInfo);
		bar.add(toolModify);
		bar.add(toolDelete);
		bar.add(toolNew);
		bar.add(toolNewSearch);
		bar.setRollover(true);
		return bar;
	}

	private void createRightClickMenu() {
		List<JMenuItem> items = new ArrayList<JMenuItem>();
		btnInfo = new FwkMenuItem(KeyEvent.VK_P, Constants.INFO_IMAGE, null, "Info");
		btnModify = new FwkMenuItem(KeyEvent.VK_M, Constants.EDIT_IMAGE, null, "Modificar");
		btnNew = new FwkMenuItem(KeyEvent.VK_N, Constants.NEW_IMAGE, null, "Nuevo");
		btnDelete = new FwkMenuItem(KeyEvent.VK_D, Constants.DELETE_IMAGE, null, "Borrar");

		items.add(btnModify);
		items.add(btnDelete);
		items.add(btnNew);
		items.add(btnInfo);
		popupMenu = FwkComponentsFactory.createPopupMenu(items);
	}

	private JPanel createResultPanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createTitledBorder("Resultados"));
		results = new SortedTable<ResourceEntity>(resultsModel);
		results.getColumn(results.getColumnName(ResultadosResourcesModel.COLUMN_NOMBRE)).setPreferredWidth(100);
		results.getColumn(results.getColumnName(ResultadosResourcesModel.COLUMN_CODIGO)).setPreferredWidth(100);
		results.getColumn(results.getColumnName(ResultadosResourcesModel.COLUMN_DESTINATION_PATH)).setPreferredWidth(
				100);
		results.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		results.setToolTipText("Doble click: Ver Foto");
		results.setAutoscrolls(true);
		JScrollPane scrRecursos = new JScrollPane(results);
		scrRecursos.setAutoscrolls(true);
		scrRecursos.setPreferredSize(new Dimension(650, 350));
		scrRecursos.setWheelScrollingEnabled(true);
		panel.add(scrRecursos);
		return panel;
	}

	private JPanel createForm() {
		JPanel form = new JPanel();
		form.setBorder(BorderFactory.createTitledBorder("Filtro"));
		form.setLayout(new FlowLayout());
		form.add(new JLabel("Nombre :"));
		form.add(txtNombre);
		form.add(new JLabel("Prefix :"));
		form.add(txtPrefix);
		form.add(new JLabel("Secuencial:"));
		form.add(txtSecuencial);
		form.add(btnFind);

		return form;
	}

	private void initComponents() {
		resultsModel = new ResultadosResourcesModel();
		results = new SortedTable<ResourceEntity>(resultsModel);
		btnFind = new FwkButton("", Constants.SEARCH_IMAGE);
		btnFind.setPreferredSize(new Dimension(30,30));

		toolNew = new FwkButton("Nuevo", Constants.NEW_IMAGE);
		toolInfo = new FwkButton("Info", Constants.INFO_IMAGE);
		toolModify = new FwkButton("Modificar", Constants.EDIT_IMAGE);
		toolDelete = new FwkButton("Eliminar", Constants.DELETE_IMAGE);
		toolNewSearch = new FwkButton("Nueva Busqueda", Constants.SEARCH_IMAGE);
		
		btnInfo = new FwkMenuItem(KeyEvent.VK_I, Constants.INFO_IMAGE, null, "Informacion");
		btnModify = new FwkMenuItem(KeyEvent.VK_M, Constants.EDIT_IMAGE, null, "Modificar");
		btnNew = new FwkMenuItem(KeyEvent.VK_N, Constants.NEW_IMAGE, null, "Nueva");
		btnDelete = new FwkMenuItem(KeyEvent.VK_D, Constants.DELETE_IMAGE, null, "Borrar");
		txtNombre = new JTextField();
		
		Dimension d = new Dimension(100, 20);
		
		txtNombre.setPreferredSize(d);
		txtPrefix = new JTextField();
		txtPrefix.setPreferredSize(d);
		txtSecuencial = new JTextField();
		txtSecuencial.setPreferredSize(d);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource().equals(btnFind)) {
			buscar();
		} else if (e.getSource().equals(btnDelete) || e.getSource().equals(toolDelete)) {
			deleteEntry();
		} else if (e.getSource().equals(btnInfo) || e.getSource().equals(toolInfo)) {
			
			
		} else if (e.getSource().equals(btnModify) || e.getSource().equals(toolModify)) {
			
		} else if (e.getSource().equals(btnNew) || e.getSource().equals(toolNew)) {
			
		} else if (e.getSource().equals(toolNewSearch)) {
			cleanSearchForm();
		}

	}

	private void deleteEntry() {
		System.out.println("");
		int i = results.getSelectedRow();
		resultsModel.deleteObject(results.getSelectedRow());
		resource.deleteField(i);
		repaint();
	}

	private void cleanSearchForm() {
		txtNombre.setText("");
		txtPrefix.setText("");
		txtSecuencial.setText("");
		results.getModel().borrarTodos();
		
	}

	private void buscar() {
		ResourceDAO dao = new ResourceDAO();
		Integer secuencial = txtSecuencial.getText().isEmpty() ? null : new Integer(txtSecuencial.getText());
		resultsModel.actualizatabla(dao.find(txtNombre.getText(), txtPrefix.getText(), secuencial));

	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent e) {
		if (e.getClickCount() == 2) {
			e.consume();
		}
		if (SwingUtilities.isRightMouseButton(e)) {
			showPopup(e);
		} else if (e.getSource().equals(results) && e.isConsumed()) {
			if (e.isConsumed()) {
//				actionPaciente(ActionType.MOSTRAR_PACIENTE);
			}
		}
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		showPopup(e);
	}

	@Override
	public void mouseEntered(MouseEvent e) {

	}

	@Override
	public void mouseExited(MouseEvent e) {
		
	}
}
